#!/usr/bin/python
#-*- coding: utf-8 -*-

print "Content-Type: text/html\n"

import cgi
import cgitb
cgitb.enable()
import random
form = cgi.FieldStorage()

#zustaende auslesen


# variablen initialisieren
# aus fieldStorage komme nur strings => immer casten
title = "CGI Rechner"
runde = int(form["runde"].value) +1 if "runde" in form else 0 # vorverarbeitung hier machen

# muss richtiges ergebnis des vorigen klicks merken
prevresult = int(form["prevresult"].value) if "prevresult" in form else None
right =  int(form["right"].value) if "right" in form else 0
userresult =  int(form["userresult"].value) if "userresult" in form else None
result = None
z1 = random.randint(1,10)
z2 = random.randint(1,10)
operator = None

def checkresult(prevresult, userresult):
    if prevresult == userresult:
        return 1
    return 0

def resultpage():
    content = """
    <h2>Ergebnis</h2><br />
    Sie haben: %d von %d Aufgaben richtig gel&ouml;sst!<br />
    <a href='rechner.cgi'>nochmal spielen</a>
    """
    return content % (right, runde)

def aufgabenpage(operator):
    content = """
    <p>
    Berechnen Sie: %d %s %d <br />
    </p>
    <form action='rechner.cgi' method='GET'>
    <input type='hidden' name='runde' value='%d'>
    <input type='hidden' name='right' value='%d'>
    <input type='hidden' name='prevresult' value='%d'>
    L&ouml;sung: <input type='text' name='userresult'><br />
    <input type='submit' value='OK'>
    """
    # runde erhoehen
    global runde
    return content % (z1, operator, z2, runde, right,result)

if runde != 0:
    """ausser in 0. runde, da gibts noch kein userinput"""
    global right
    right += checkresult(prevresult, userresult)
 


if runde < 3:
    """additionsaufgabe"""
    result = z1 + z2
    operator = "+"
    content = aufgabenpage(operator)
elif runde < 6:
    """multiplikationsaufgabe"""
    result = z1 * z2
    operator = "*"
    content = aufgabenpage(operator)

if runde >= 6:
    content = resultpage()

tmpl = """
<html>
<head><title>%s</title></head>
<body>%s</body>
</html>
"""

# ausgabe
print tmpl % (title, content)

